package com.hqs.rxjava;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

import java.lang.annotation.Annotation;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnTextChanged;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;

public class SumActivity extends AppCompatActivity {

    @BindView(R.id.et1)
    EditText et1;

    @BindView(R.id.et2)
    EditText et2;

    @BindView(R.id.tv_result)
    TextView tvResult;

    Observer observer;
    Disposable mDispose;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sum);

        ButterKnife.bind(this);

        observer = new Observer<Integer>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                mDispose = d;
            }

            @Override
            public void onNext(@NonNull Integer integer) {
                tvResult.setText(integer.toString());
            }

            @Override
            public void onError(@NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };

        PublishSubject.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Integer> e) throws Exception {

            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    @OnTextChanged({R.id.et1, R.id.et2})
    void onValueChanged(){
        int num1 = 0;
        int num2 = 0;
        try {
            num1 = Integer.parseInt(et1.getText().toString());
            num2 = Integer.parseInt(et2.getText().toString());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        observer.onNext(num1 + num2);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDispose.dispose();
    }
}
